<?php

namespace app\agent\model\agent;

use app\agent\model\BaseModel;
use think\Db;
use think\Session;
use utils\Random;
use think\Config;

/**
 * 商家用户模型
 * Class StoreUser
 * @package app\store\model
 */
class User extends BaseModel
{

    protected $name = 'agent_user';

    /**
     * 关联微信代理商表
     * @return \think\model\relation\BelongsTo
     */
    public function agent()
    {

        $module = self::getCalledModule() ?: 'common';
        return $this->belongsTo("app\\{$module}\\model\\agent\\Agent");

    }

    /**
     * 关联用户角色表表
     * @return \think\model\relation\BelongsToMany
     */
    public function role()
    {
        return $this->belongsToMany('Role', 'AgentUserRole');
    }


    public function add($data){
        return $this->allowField(true)->save($data);
    }

    public function upd($data,$agentId){
        return $this->allowField(true)->save($data,['agent_user_id'=>$agentId]);
    }

    /**
     * 验证用户名是否重复
     * @param $userName
     * @return bool
     */
    public static function checkExist($userName)
    {
        return !!static::useGlobalScope(false)
            ->where('user_name', '=', $userName)
            ->where('is_delete', '=', 0)
            ->value('agent_user_id');
    }

    /**
     * 商家用户详情
     * @param $where
     * @param array $with
     * @return static|null
     * @throws \think\exception\DbException
     */
    public static function detail($where, $with = [])
    {
        !is_array($where) && $where = ['agent_user_id' => (int)$where];
        return static::get(array_merge(['is_delete' => 0], $where), $with);
    }

    /**
     * 更新当前代理信息
     * @param $data
     * @return bool
     */
  //  public function renew($data,$agent_user_id)
      public function renew($data,$agent_user_id){
          if ($data['password'] !== $data['password_confirm']) {
                $this->error = '确认密码不正确';
                return false;
            }
            $salt= Random::alnum();
            // 更新管理员信息
            if ($this->save([
                'user_name'=> $data['user_name'],
                'salt'     =>$salt,
                'password' => md5(md5($data['password'].$salt.config('salt'))),
                ]) === false) {
                return false;
            }
            //修改agent信息
            Db::name('agent')->where(['agent_id'=>$agent_user_id])->update([
                'user_name'=> $data['user_name'],
                'salt'     =>$salt,
                'password' => md5(md5($data['password'].$salt.config('salt'))),
            ]);
            // 更新session
           Session::clear('yoshop_agent');
           return true;
      }


    /**
     * 保存登录状态
     * @param $user
     * @throws \think\Exception
     */
    public function loginState($user){
        // 保存登录状态
        $agentUser=Db::name('agent_user')->where(['agent_user_id'=>$user['agent_id']])->find();
        Session::set('yoshop_agent', [
            'user' => [
                'agent_user_id' => $user['agent_id'],
                'user_name' => $user['user_name'],
            ],
            'agent' => $agentUser,
            'is_login' => true,
        ]);
    }

    /**
     * 获取用户列表
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getList()
    {
        return Db::name('agent_user')
            ->where('is_delete', '=', 0)
            ->order(['create_time' => 'desc'])
            ->paginate(15, false, [
                'query' => request()->request()
            ]);
    }

    /**
     * 删除小程序下的商家用户
     * @param $agentId
     * @return false|int
     */
    public function setDelete()
    {
        return $this->save(['is_delete' => 1]);
    }

}
